package entity

import (
	"github.com/golang/protobuf/proto"
	"kop/modules/island/configuration"
	"kop/pb"
	"kop/pb/service"
	"time"
)

type Island struct {
	IslandID     int32  `gorm:"type:int;primary_key"` //
	ServerID     int32  `gorm:"type:int;primary_key"` //
	RoleID       int32  // 后续加索引
	RoleName     string //
	GuildID      int32
	GuildName    string
	CaptainsData []byte    // proto.Marshal(self.CaptainIDs1)
	Time         time.Time // 占领时间
	CreatedAt    time.Time
	UpdatedAt    time.Time

	Captains *service.Captains `sql:"-"`
}

func (i *Island) Reset() {

	i.RoleID = 0
	i.GuildID = 0
	i.RoleName = ""
	i.GuildName = ""
	i.Time = time.Time{}
	i.Captains = nil
}

func NewIsland(islandID, serverID int32) *Island {
	return &Island{IslandID: islandID, ServerID: serverID}
}

func (i *Island) TimeOver() bool {

	return i.Minutes() >= 60*3
}

// 占领分钟
func (i *Island) Minutes() int32 {

	var max int32 = 60 * 3

	var minutes = int32(time.Now().Sub(i.Time).Minutes())
	if minutes > max {
		minutes = max
	}

	return minutes
}

// 物资
func (i *Island) Total() int32 {

	return i.Minutes() * configuration.GetByIslandID(i.IslandID).Income
}

func (i *Island) AfterFind() error {

	if len(i.CaptainsData) > 0 {

		i.Captains = &service.Captains{}
		return proto.Unmarshal(i.CaptainsData, i.Captains)
	}

	return nil
}

func (i *Island) BeforeSave() (err error) {

	i.CaptainsData, err = proto.Marshal(i.Captains)
	return err
}

func (i *Island) BeforeUpdate() (err error) {

	i.CaptainsData, err = proto.Marshal(i.Captains)
	return err
}

func (i *Island) SetCaptains(captains []*pb.Captain) {
	i.Captains = &service.Captains{Captains: captains}
}
